/* eslint-disable camelcase */
import axios from 'axios';
import Cookies from 'js-cookie';
import config from './config';
import router from '@/router';
import { Toast } from 'vant';

export default function $request(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            baseURL: config.baseUrl,
            headers: options.headers || config.headers,
            timeout: config.timeout,
            withCredentials: config.withCredentials

        });
        // request 拦截器
        instance.interceptors.request.use(
            config => {
                // 在发送之前做点什么
                const auth_token = Cookies.get('auth_token');
                if (auth_token) {
                    config.headers.auth_token = auth_token;
                } else {
                    const loginpage = Cookies.get('loginpage');
                    if (loginpage) {
                        router.push('/login');
                    }
                }
                if (config.method === 'post') { }
                return config;
            },
            error => {
                // 判断请求超时
                if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
                    Toast('信号不好，请求超时')
                }
            }

        );

        // response 拦截器
        instance.interceptors.response.use(
            response => {
                // 对响应数据做点什么
                const res = response
                if (res.data.code !== 1) {
                    Toast({
                        message: res.data.message || '不明错误',
                        type: 'error',
                        duration: 5 * 1000
                    })
                }
                // if the custom code is not 20000, it is judged as an error.
                if (res.status !== 200) {
                    Toast({
                        message: res.message || '不明错误',
                        type: 'error',
                        duration: 5 * 1000
                    })
                    return Promise.reject(new Error(res.message || 'Error'))
                } else {
                    return res.data;
                }
            },
            err => {
                if (err && err.response) {
                    console.log(err)
                }// 返回接口返回的错误信息
                return Promise.reject(err);
            }
        );
        // 请求处理
        instance(options).then(res => {
            resolve(res);
            return false;
        }).catch(error => {
            reject(error);
        });
    });
}
